<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">






  
  
  <link rel="stylesheet" media="all" href="/blog/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="python," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.2" />






<meta name="description" content="1.输入与输出 input()和print()是在命令行下面最基本的输入和输出 input()返回的数据类型是str name=input(&amp;apos;please input your name:&amp;apos;) print(&amp;quot;hello&amp;quot;,name)   2.数据类型与变量 在Python中，能够直接处理的数据类型有以下几种： 整数、浮点数 无论整数做//除法还是取余数，结果">
<meta name="keywords" content="python">
<meta property="og:type" content="article">
<meta property="og:title" content="python学习笔记">
<meta property="og:url" content="https://git.oschina.net/choichumgming/blog/2017/08/19/python学习笔记（一）/index.html">
<meta property="og:site_name" content="choichumgming&#39;s blog">
<meta property="og:description" content="1.输入与输出 input()和print()是在命令行下面最基本的输入和输出 input()返回的数据类型是str name=input(&amp;apos;please input your name:&amp;apos;) print(&amp;quot;hello&amp;quot;,name)   2.数据类型与变量 在Python中，能够直接处理的数据类型有以下几种： 整数、浮点数 无论整数做//除法还是取余数，结果">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-12-26T08:35:48.753Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="python学习笔记">
<meta name="twitter:description" content="1.输入与输出 input()和print()是在命令行下面最基本的输入和输出 input()返回的数据类型是str name=input(&amp;apos;please input your name:&amp;apos;) print(&amp;quot;hello&amp;quot;,name)   2.数据类型与变量 在Python中，能够直接处理的数据类型有以下几种： 整数、浮点数 无论整数做//除法还是取余数，结果">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://git.oschina.net/choichumgming/blog/2017/08/19/python学习笔记（一）/"/>





  <title>python学习笔记 | choichumgming's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">choichumgming's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">stay foolish,stay hard</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/blog/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      
        
        <li class="menu-item menu-item-board">
          <a href="/blog/board/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            留言
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://git.oschina.net/choichumgming/blog/blog/2017/08/19/python学习笔记（一）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="choichumgming">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="choichumgming's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">python学习笔记</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-19T00:07:14+08:00">
                2017-08-19
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/python/" itemprop="url" rel="index">
                    <span itemprop="name">python</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/blog/2017/08/19/python学习笔记（一）/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2017/08/19/python学习笔记（一）/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <h2 id="1-输入与输出"><a href="#1-输入与输出" class="headerlink" title="1.输入与输出"></a><font size="4">1.输入与输出</font></h2><ol>
<li>input()和print()是在命令行下面最基本的输入和输出</li>
<li><p>input()返回的数据类型是str</p>
<pre><code>name=input(&apos;please input your name:&apos;)
print(&quot;hello&quot;,name)
</code></pre></li>
</ol>
<h2 id="2-数据类型与变量"><a href="#2-数据类型与变量" class="headerlink" title="2.数据类型与变量"></a><font size="4">2.数据类型与变量</font></h2><ol>
<li>在Python中，能够直接处理的数据类型有以下几种：<ul>
<li>整数、浮点数<ol>
<li>无论整数做//除法还是取余数，结果永远是整数，所以，整数运算结果永远是精确的。</li>
<li>整数和浮点数在计算机内部存储的方式是不同的，整数运算永远是精确的（除法难道也是精确的？是的！），而浮点数运算则可能会有四舍五入的误差。）</li>
</ol>
<ul>
<li>字符串：是以单引号’或双引号”括起来的任意文本<ol>
<li>如果字符串内部既包含’又包含”怎么办？可以用转义字符\来标识</li>
<li>Python还允许用r’’表示’’内部的字符串默认不转义  </li>
<li>如果字符串内部有很多换行，用\n写在一行里不好阅读，为了简化，Python允许用r’’表示’’内部的字符串默认不转义</li>
</ol>
</li>
<li>布尔值：布尔值可以用and、or和not运算</li>
<li>空值：是Python里一个特殊的值，用None表示。None不能理解为0，因为0是有意义的，而None是一个特殊的空值。</li>
<li>变量：在Python中，等号=是赋值语句，可以把任意数据类型赋值给变量，同一个变量可以反复赋值，而且可以是不同类型的变量</li>
</ul>
</li>
</ul>
</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">	</div><div class="line">print(<span class="string">'''line1</span></div><div class="line"><span class="string"><span class="meta">... </span>line2</span></div><div class="line"><span class="string"> ... line3'''</span>)</div><div class="line"></div><div class="line">print(<span class="string">'\\\t\\'</span>) <span class="comment">#\       \</span></div><div class="line">print(<span class="string">r'\\\t\\'</span>) <span class="comment">#\\\t\\</span></div></pre></td></tr></table></figure>
<h2 id="3-字符串与编码"><a href="#3-字符串与编码" class="headerlink" title="3.字符串与编码"></a><font size="4"><a href="https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431664106267f12e9bef7ee14cf6a8776a479bdec9b9000" target="_blank" rel="external">3.字符串与编码</a></font></h2><h2 id="4-list-and-tuple"><a href="#4-list-and-tuple" class="headerlink" title="4.list and tuple"></a><font size="4">4.list and tuple</font></h2><h3 id="list"><a href="#list" class="headerlink" title="list "></a><font size="3">list </font></h3><ol>
<li><p>list是一种有序的集合，可以随时添加和删除其中的元素，list里面的元素的数据类型也可以不同</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">stu = [<span class="string">'a'</span>,<span class="string">'b'</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">2.3</span>]</div></pre></td></tr></table></figure>
</li>
<li><p>用len()函数可以获得list元素的个数</p>
</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">print(<span class="string">"stu:"</span>,stu,<span class="string">'len:'</span>,len(stu))</div></pre></td></tr></table></figure>
<ol>
<li><p>用索引来访问list中每一个位置的元素</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">print(<span class="string">'stu0:'</span>,stu[<span class="number">0</span>],<span class="string">'stu1:'</span>,stu[<span class="number">1</span>],<span class="string">'stu2:'</span>,stu[<span class="number">2</span>])</div></pre></td></tr></table></figure>
</li>
<li><p>list是一个可变的有序表，所以，可以往list中追加元素到末尾</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">stu.append(<span class="number">1</span>)</div><div class="line">print(stu)</div></pre></td></tr></table></figure>
</li>
<li><p>也可以把元素插入到指定的位置，比如索引号为1的位置</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">stu.insert(<span class="number">2</span>,<span class="string">'cool'</span>)</div><div class="line">print(stu)</div></pre></td></tr></table></figure>
</li>
<li><p>要删除指定位置的元素，用pop(i)方法，其中i是索引位置</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">stu.pop()</div><div class="line">print(stu)</div></pre></td></tr></table></figure>
</li>
<li><p>要把某个元素替换成别的元素，可以直接赋值给对应的索引位置</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">stu[<span class="number">2</span>]=<span class="number">3333</span></div><div class="line">print(stu)</div></pre></td></tr></table></figure>
</li>
<li><p>list元素也可以是另一个list</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">stu1=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>]</div><div class="line">stu.insert(<span class="number">2</span>,stu1)</div></pre></td></tr></table></figure>
</li>
<li><p>因此stu可以看成是一个二维数组，类似的还有三维、四维……数组，不过很少用到。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">print(stu[<span class="number">2</span>][<span class="number">2</span>])</div></pre></td></tr></table></figure>
</li>
<li><p>list有个神奇的切片方法：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">list(range(<span class="number">100</span>))[<span class="number">5</span>:<span class="number">10</span>]</div></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="tuple"><a href="#tuple" class="headerlink" title="tuple"></a><font size="3">tuple</font></h3><ol>
<li>tuple和list非常类似，但是tuple一旦初始化就不能修改</li>
<li>tuple所谓的“不变”是说，tuple的每个元素，指向永远不变</li>
<li>没有append()，insert()这样的方法。其他获取元素的方法和list是一样的</li>
<li>其中的元素不能复制成另外的元素 tuple的陷阱：当你定义一个tuple时，在定义的时候，tuple的元素就必须被确定下来</li>
<li>只有1个元素的tuple定义时必须加一个逗号 eg:t=(1,)<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">t=(<span class="number">1</span>,)</div><div class="line">print(type(t))</div><div class="line">t=(<span class="number">1</span>)</div><div class="line">print(type(t))</div></pre></td></tr></table></figure>
</li>
</ol>
<h2 id="5-循环"><a href="#5-循环" class="headerlink" title="5.循环"></a><font size="4">5.循环</font></h2><p>1.Python的循环有两种，一种是for…in循环，依次把list或tuple中的每个元素迭代出来<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">stu = [<span class="string">'a'</span>,<span class="string">'b'</span>,<span class="string">'c'</span>,<span class="string">'aa'</span>,<span class="string">'bb'</span>,<span class="string">'cc'</span>]</div><div class="line">s=str()</div><div class="line"><span class="keyword">for</span> ss <span class="keyword">in</span> stu:</div><div class="line">    print(ss)</div><div class="line">    s+=ss</div><div class="line">print(s)</div></pre></td></tr></table></figure></p>
<ol>
<li>Python提供一个range()函数，可以生成一个整数序列，再通过list()函数可以转换为list<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">numList=list(range(<span class="number">0</span>,<span class="number">100</span>,<span class="number">2</span>))</div><div class="line">print(numList)</div><div class="line"><span class="comment"># while循环</span></div><div class="line">sum = <span class="number">0</span></div><div class="line">n = <span class="number">99</span></div><div class="line"><span class="keyword">while</span> n &gt; <span class="number">0</span>:</div><div class="line">    sum = sum + n</div><div class="line">    n = n - <span class="number">2</span></div><div class="line">print(sum)</div></pre></td></tr></table></figure>
</li>
</ol>
<h2 id="6-dict-and-set"><a href="#6-dict-and-set" class="headerlink" title="6.dict and set "></a><font size="4">6.dict and set </font></h2><h3 id="dictionary"><a href="#dictionary" class="headerlink" title="dictionary"></a><font size="3">dictionary</font></h3><ol>
<li><p>把数据放入dict的方法，除了初始化时指定外，还可以通过key放入</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">dic=&#123;<span class="string">"choi"</span>:<span class="number">100</span>,<span class="string">"lv"</span>:<span class="number">0</span>,<span class="string">'sa'</span>:<span class="number">23</span>&#125;</div><div class="line">b=list(dic.values())</div><div class="line">c=list(dic.keys())</div><div class="line">print(b,c,type(b),type(c))</div></pre></td></tr></table></figure>
</li>
<li><p>由于一个key只能对应一个value，所以，多次对一个key放入value，后面的值会把前面的值冲掉,如果key不存在，dict就会报错</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">dic[<span class="string">'lv'</span>]=<span class="number">99.9</span></div><div class="line">print(dic[<span class="string">'lv'</span>])</div></pre></td></tr></table></figure>
</li>
<li><p>要避免key不存在的错误，有两种办法，</p>
</li>
</ol>
<ul>
<li>一是通过in判断key是否存在</li>
<li>二是通过dict提供的get方法，如果key不存在，可以返回None，或者自己指定的value<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#way one</span></div><div class="line">judge=<span class="string">"lv"</span> <span class="keyword">in</span> dic</div><div class="line">print(judge)</div><div class="line"></div><div class="line"><span class="comment">#way tow</span></div><div class="line">judge=dic.get(<span class="string">'ss'</span>)</div><div class="line">print(judge)</div><div class="line">judge=dic.get(<span class="string">'ss'</span>,<span class="number">-2</span>)</div><div class="line">print(judge)</div></pre></td></tr></table></figure>
</li>
</ul>
<ol>
<li><p>要删除一个key，用pop(key)方法，对应的value也会从dict中删除</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">dic.pop(<span class="string">'choi'</span>)</div><div class="line">print(dic)</div></pre></td></tr></table></figure>
</li>
<li><p>请务必注意，dict内部存放的顺序和key放入的顺序是没有关系的。</p>
</li>
<li>和list比较，dict有以下几个特点：<ul>
<li>查找和插入的速度极快，不会随着key的增加而变慢；</li>
<li>需要占用大量的内存，内存浪费多。<br>而list相反：</li>
<li>查找和插入的时间随着元素的增加而增加；</li>
<li>占用空间小，浪费内存很少。<br>所以，dict是用空间来换取时间的一种方法。正确使用dict非常重要，需要牢记的第一条就是dict的key必须是不可变对象</li>
</ul>
</li>
</ol>
<h3 id="set"><a href="#set" class="headerlink" title="set"></a><font size="3">set</font></h3><ol>
<li>set和dict类似，也是一组key的集合，但不存储value。由于key不能重复，所以，在set中，没有重复的key。</li>
<li><p>要创建一个set，需要提供一个list作为输入集合：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">s= set([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">33</span>,<span class="number">3</span>,<span class="number">5</span>])</div><div class="line">print(s,type(s))<span class="comment">#重复元素在set中自动被过滤</span></div></pre></td></tr></table></figure>
</li>
<li><p>通过add(key)方法可以添加元素到set中，可以重复添加，但不会有效果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">s.add(<span class="number">999</span>)</div><div class="line">print(s)</div></pre></td></tr></table></figure>
</li>
<li><p>通过remove(key)方法可以删除元素</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">s.remove(<span class="number">999</span>)</div><div class="line">print(s)</div></pre></td></tr></table></figure>
</li>
<li><p>set可以看成数学意义上的无序和无重复元素的集合，因此，两个set可以做数学意义上的交集、并集等操作</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">s1= set([<span class="number">2</span>,<span class="number">0</span>,<span class="number">3</span>,<span class="number">6</span>,<span class="number">5</span>])</div><div class="line">s2= set([<span class="number">2</span>,<span class="number">9</span>,<span class="number">7</span>,<span class="number">88</span>,<span class="number">6</span>,<span class="number">5</span>])</div><div class="line">print(s1 &amp; s2)</div><div class="line">print(s1 | s2)</div></pre></td></tr></table></figure>
</li>
<li><p>set和dict的唯一区别仅在于没有存储对应的value，但是，set的原理和dict一样，所以，同样不可以放入可变对象，因为无法判断两个可变对象是否相等，也就无法保证set内部“不会有重复元素”。试试把list放入set，看看是否会报错</p>
<h2 id="7-不可变对象"><a href="#7-不可变对象" class="headerlink" title="7.不可变对象"></a><font size="4">7.不可变对象</font></h2><p>对于不变对象来说，调用对象自身的任意方法，也不会改变该对象自身的内容。相反，这些方法会创建新的对象并返回，这样，就保证了不可变对象本身永远是不可变的。</p>
</li>
</ol>
<h2 id="8-默认参数"><a href="#8-默认参数" class="headerlink" title="8.默认参数"></a><font size="4">8.默认参数</font></h2><ol>
<li>如何设置默认参数:<br> 当函数有多个参数时，把变化大的参数放前面，变化小的参数放后面。变化小的参数就可以作为默认参数。</li>
<li>定义默认参数要牢记一点：<br> 默认参数必须指向不变对象</li>
<li>为什么要设计str、None这样的不变对象呢？<br> 因为不变对象一旦创建，对象内部的数据就不能修改，这样就减少了由于修改数据导致的错误。</li>
<li>此外，由于对象不变，多任务环境下同时读取对象不需要加锁，同时读一点问题都没有。</li>
<li>我们在编写程序时，如果可以设计一个不变对象，那就尽量设计成不变对象。<h2 id="9-可变参数"><a href="#9-可变参数" class="headerlink" title="9.可变参数"></a><font size="4">9.可变参数</font></h2></li>
<li>顾名思义，可变参数就是传入的参数个数是可变的，可以是1个、2个到任意个，还可以是0个。</li>
<li>定义可变参数和定义一个list或tuple参数相比，仅仅在参数前面加了一个*号。</li>
<li>在函数内部，参数numbers接收到的是一个tuple，因此，函数代码完全不变。</li>
<li>但是，调用该函数时，可以传入任意个参数，包括0个参数：</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">calc</span><span class="params">(*numbers)</span>:</span></div><div class="line">    sum = <span class="number">0</span></div><div class="line">    <span class="keyword">for</span> n <span class="keyword">in</span> numbers:</div><div class="line">        sum = sum + n * n</div><div class="line">    <span class="keyword">return</span> sum</div></pre></td></tr></table></figure>
<ol>
<li>如果已经有一个list或者tuple，要调用一个可变参数怎么办<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">nums = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</div><div class="line">calc(*nums)</div></pre></td></tr></table></figure>
</li>
</ol>
<h2 id="10-关键字参数"><a href="#10-关键字参数" class="headerlink" title="10.关键字参数"></a><font size="4">10.关键字参数</font></h2><ol>
<li>关键字参数允许你传入0个或任意个含参数名的参数，这些关键字参数在函数内部自动组装为一个dict</li>
<li><p>关键字参数有什么用？它可以扩展函数的功能。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">person</span><span class="params">(name, age, **kw)</span>:</span></div><div class="line">    print(<span class="string">'name:'</span>, name, <span class="string">'age:'</span>, age, <span class="string">'other:'</span>, kw)</div></pre></td></tr></table></figure>
</li>
<li><p>注意kw获得的dict是extra的一份拷贝，对kw的改动不会影响到函数外的extra</p>
</li>
<li>对于关键字参数，函数的调用者可以传入任意不受限制的关键字参数。至于到底传入了哪些，就需要在函数内部通过kw检查。</li>
<li>以person()函数为例，我们希望检查是否有city和job参数：<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">person</span><span class="params">(name, age, **kw)</span>:</span></div><div class="line">    <span class="keyword">if</span> <span class="string">'city'</span> <span class="keyword">in</span> kw:</div><div class="line">        <span class="comment"># 有city参数</span></div><div class="line">        <span class="keyword">pass</span></div><div class="line">    <span class="keyword">if</span> <span class="string">'job'</span> <span class="keyword">in</span> kw:</div><div class="line">        <span class="comment"># 有job参数</span></div><div class="line">        <span class="keyword">pass</span></div><div class="line">    print(<span class="string">'name:'</span>, name, <span class="string">'age:'</span>, age, <span class="string">'other:'</span>, kw)</div></pre></td></tr></table></figure>
</li>
</ol>
<p>但是调用者仍可以传入不受限制的关键字参数：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">person(<span class="string">'Jack'</span>, <span class="number">24</span>, city=<span class="string">'Beijing'</span>, addr=<span class="string">'Chaoyang'</span>, zipcode=<span class="number">123456</span>)</div></pre></td></tr></table></figure></p>
<ol>
<li><p>如果要限制关键字参数的名字，就可以用命名关键字参数， 例如，只接收city和job作为关键字参数。这种方式定义的函数如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">person</span><span class="params">(name, age, *, city, job)</span>:</span></div><div class="line">    print(name, age, city, job)</div></pre></td></tr></table></figure>
</li>
<li><p>和关键字参数<em>*kw不同，命名关键字参数需要一个特殊分隔符</em>，*后面的参数被视为命名关键字参数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">person(<span class="string">'Jack'</span>, <span class="number">24</span>, city=<span class="string">'Beijing'</span>, job=<span class="string">'Engineer'</span>)</div></pre></td></tr></table></figure>
</li>
<li><p>如果函数定义中已经有了一个可变参数，后面跟着的命名关键字参数就不再需要一个特殊分隔符*了：</p>
</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">person</span><span class="params">(name, age, *args, city, job)</span>:</span></div><div class="line">    print(name, age, args, city, job)</div></pre></td></tr></table></figure>
<ol>
<li><p>命名关键字参数必须传入参数名，这和位置参数不同。如果没有传入参数名，调用将报错</p>
</li>
<li><p>命名关键字参数可以有缺省值，从而简化调用：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">person</span><span class="params">(name, age, *, city=<span class="string">'Beijing'</span>, job)</span>:</span></div><div class="line">    print(name, age, city, job)</div></pre></td></tr></table></figure>
</li>
<li><p>由于命名关键字参数city具有默认值，调用时，可不传入city参数</p>
</li>
</ol>
<h2 id="11-参数组合"><a href="#11-参数组合" class="headerlink" title="11.参数组合"></a><font size="4">11.参数组合</font></h2><ol>
<li>在Python中定义函数，可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数，这5种参数都可以组合使用。</li>
<li>但是请注意，参数定义的顺序必须是：<strong>必选参数、默认参数、可变参数、命名关键字参数和关键字参数 </strong>。</li>
<li><p>比如定义一个函数，包含上述若干种参数：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">f1</span><span class="params">(a, b, c=<span class="number">0</span>, *args, **kw)</span>:</span></div><div class="line">    print(<span class="string">'a ='</span>, a, <span class="string">'b ='</span>, b, <span class="string">'c ='</span>, c, <span class="string">'args ='</span>, args, <span class="string">'kw ='</span>, kw)</div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">f2</span><span class="params">(a, b, c=<span class="number">0</span>, *, d, **kw)</span>:</span></div><div class="line">    print(<span class="string">'a ='</span>, a, <span class="string">'b ='</span>, b, <span class="string">'c ='</span>, c, <span class="string">'d ='</span>, d,<span class="string">'kw ='</span>, kw)</div></pre></td></tr></table></figure>
</li>
<li><p>对于任意函数，都可以通过类似func(<em>args, *</em>kw)的形式调用它，无论它的参数是如何定义的。</p>
<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a><font size="4">小结</font></h2></li>
<li>Python的函数具有非常灵活的参数形态，既可以实现简单的调用，又可以传入非常复杂的参数。</li>
<li>默认参数一定要用不可变对象，如果是可变对象，程序运行时会有逻辑错误！</li>
<li>要注意定义可变参数和关键字参数的语法<br> <strong>*args是可变参数，args接收的是一个tuple</strong><br> <strong>**kw是关键字参数，kw接收的是一个dict </strong></li>
<li>以及调用函数时如何传入可变参数和关键字参数的语法：<br><strong>可变参数既可以直接传入：func(1, 2, 3)，又可以先组装list或tuple，再通过<em>args传入：func(</em>(1, 2, 3))；</strong><br><strong>关键字参数既可以直接传入：func(a=1, b=2)，又可以先组装dict，再通过**kw传入：func(**{‘a’: 1, ‘b’: 2})。</strong><br>使用<em>args和*</em>kw是Python的习惯写法，当然也可以用其他参数名，但最好使用习惯用法。</li>
<li>命名的关键字参数是为了限制调用者可以传入的参数名，同时可以提供默认值。</li>
<li>定义命名的关键字参数在没有可变参数的情况下不要忘了写分隔符*，否则定义的将是位置参数。</li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/python/" rel="tag"># python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2017/09/19/int、long、long long取值范围/" rel="prev" title="int、long、long long取值范围">
                int、long、long long取值范围 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <!--PC版-->
<div id="SOHUCS" ></div>


    

  </div>
     <div class="comments" id="comments">
       
     </div>
   





        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/avatar.gif"
               alt="choichumgming" />
          <p class="site-author-name" itemprop="name">choichumgming</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives/">
                <span class="site-state-item-count">15</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories/index.html">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">标签</span>
              
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="http://www.weibo.com/u/2558763801" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                    
                      微博
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-输入与输出"><span class="nav-number">1.</span> <span class="nav-text">1.输入与输出</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-数据类型与变量"><span class="nav-number">2.</span> <span class="nav-text">2.数据类型与变量</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-字符串与编码"><span class="nav-number">3.</span> <span class="nav-text">3.字符串与编码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-list-and-tuple"><span class="nav-number">4.</span> <span class="nav-text">4.list and tuple</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#list"><span class="nav-number">4.1.</span> <span class="nav-text">list </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#tuple"><span class="nav-number">4.2.</span> <span class="nav-text">tuple</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-循环"><span class="nav-number">5.</span> <span class="nav-text">5.循环</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-dict-and-set"><span class="nav-number">6.</span> <span class="nav-text">6.dict and set </span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#dictionary"><span class="nav-number">6.1.</span> <span class="nav-text">dictionary</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#set"><span class="nav-number">6.2.</span> <span class="nav-text">set</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-不可变对象"><span class="nav-number">7.</span> <span class="nav-text">7.不可变对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-默认参数"><span class="nav-number">8.</span> <span class="nav-text">8.默认参数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#9-可变参数"><span class="nav-number">9.</span> <span class="nav-text">9.可变参数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#10-关键字参数"><span class="nav-number">10.</span> <span class="nav-text">10.关键字参数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#11-参数组合"><span class="nav-number">11.</span> <span class="nav-text">11.参数组合</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#小结"><span class="nav-number">12.</span> <span class="nav-text">小结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">choichumgming</span>

  
</div>


  <div class="powered-by">
    由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
  </div>

  <span class="post-meta-divider">|</span>

  <div class="theme-info">
    主题 &mdash;
    <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
      NexT.Gemini
    </a>
  </div>


        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytnT5dky';
      var conf = '56c170b7352bd027682e3707e9eb5071';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  





  





  

  

  

  

  

  

</body>
</html>
